/**
 * 存储localStorage
 */
export const saveStore = (name, content) => {
	if(!name) return;
	if(typeof content !== 'string') {
		content = JSON.stringify(content);
	}
	window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
	if(!name) return;
	return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
	if(!name) return;
	window.localStorage.removeItem(name);
}

/**
 * 获取style样式
 */
export const getStyle = (element, attr, NumberMode = 'int') => {
	let target;
	// scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
	if(attr === 'scrollTop') {
		target = element.scrollTop;
	} else if(element.currentStyle) {
		target = element.currentStyle[attr];
	} else {
		target = document.defaultView.getComputedStyle(element, null)[attr];
	}
	//在获取 opactiy 时需要获取小数 parseFloat
	return NumberMode == 'float' ? parseFloat(target) : parseInt(target);
}
/**
 * 获取类
 */
export const getElementsByClassName = (cl) => {
	var retnode = [];
	var myclass = new RegExp('\\b' + cl + '\\b');
	var elem = document.getElementsByTagName('*');
	for(var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if(myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

/**
 * 运动效果
 * @param {HTMLElement} element   运动对象，必选
 * @param {JSON}        target    属性：目标值，必选
 * @param {number}      duration  运动时间，可选
 * @param {string}      mode      运动模式，可选
 * @param {function}    callback  可选，回调函数，链式动画
 */
export const animate = (element, target, duration = 400, mode = 'ease-out', callback) => {
	clearInterval(element.timer);

	//判断不同参数的情况
	if(duration instanceof Function) {
		callback = duration;
		duration = 400;
	} else if(duration instanceof String) {
		mode = duration;
		duration = 400;
	}

	//判断不同参数的情况
	if(mode instanceof Function) {
		callback = mode;
		mode = 'ease-out';
	}

	//获取dom样式
	const attrStyle = attr => {
		if(attr === "opacity") {
			return Math.round(getStyle(element, attr, 'float') * 100);
		} else {
			return getStyle(element, attr);
		}
	}
	//根字体大小，需要从此将 rem 改成 px 进行运算
	const rootSize = parseFloat(document.documentElement.style.fontSize);

	const unit = {};
	const initState = {};

	//获取目标属性单位和初始样式值
	Object.keys(target).forEach(attr => {
		if(/[^\d^\.]+/gi.test(target[attr])) {
			unit[attr] = target[attr].match(/[^\d^\.]+/gi)[0] || 'px';
		} else {
			unit[attr] = 'px';
		}
		initState[attr] = attrStyle(attr);
	});

	//去掉传入的后缀单位
	Object.keys(target).forEach(attr => {
		if(unit[attr] == 'rem') {
			target[attr] = Math.ceil(parseInt(target[attr]) * rootSize);
		} else {
			target[attr] = parseInt(target[attr]);
		}
	});

	let flag = true; //假设所有运动到达终点
	const remberSpeed = {}; //记录上一个速度值,在ease-in模式下需要用到
	element.timer = setInterval(() => {
		Object.keys(target).forEach(attr => {
			let iSpeed = 0; //步长
			let status = false; //是否仍需运动
			let iCurrent = attrStyle(attr) || 0; //当前元素属性址
			let speedBase = 0; //目标点需要减去的基础值，三种运动状态的值都不同
			let intervalTime; //将目标值分为多少步执行，数值越大，步长越小，运动时间越长
			switch(mode) {
				case 'ease-out':
					speedBase = iCurrent;
					intervalTime = duration * 5 / 400;
					break;
				case 'linear':
					speedBase = initState[attr];
					intervalTime = duration * 20 / 400;
					break;
				case 'ease-in':
					let oldspeed = remberSpeed[attr] || 0;
					iSpeed = oldspeed + (target[attr] - initState[attr]) / duration;
					remberSpeed[attr] = iSpeed
					break;
				default:
					speedBase = iCurrent;
					intervalTime = duration * 5 / 400;
			}
			if(mode !== 'ease-in') {
				iSpeed = (target[attr] - speedBase) / intervalTime;
				iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
			}
			//判断是否达步长之内的误差距离，如果到达说明到达目标点
			switch(mode) {
				case 'ease-out':
					status = iCurrent != target[attr];
					break;
				case 'linear':
					status = Math.abs(Math.abs(iCurrent) - Math.abs(target[attr])) > Math.abs(iSpeed);
					break;
				case 'ease-in':
					status = Math.abs(Math.abs(iCurrent) - Math.abs(target[attr])) > Math.abs(iSpeed);
					break;
				default:
					status = iCurrent != target[attr];
			}

			if(status) {
				flag = false;
				//opacity 和 scrollTop 需要特殊处理
				if(attr === "opacity") {
					element.style.filter = "alpha(opacity:" + (iCurrent + iSpeed) + ")";
					element.style.opacity = (iCurrent + iSpeed) / 100;
				} else if(attr === 'scrollTop') {
					element.scrollTop = iCurrent + iSpeed;
				} else {
					element.style[attr] = iCurrent + iSpeed + 'px';
				}
			} else {
				flag = true;
			}

			if(flag) {
				clearInterval(element.timer);
				if(callback) {
					callback();
				}
			}
		})
	}, 20);
}

//格式化参数
export const formatParams = (data) => {
	var arr = [];
	for(var name in data) {
		arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
	}
	arr.push(("v=" + Math.random()).replace(".", ""));
	return arr.join("&");
}

//时间格式转化
export const formatTime = (str) => {
	if(parseInt(str) < 10) {
		return "0" + str;
	}
	return str;
}

//将时分秒转化为秒
export const commenTimeToSecondTime = (time) => {
	let s = '';
	let hour = Number(time.split(':')[0]);
	let min = Number(time.split(':')[1]);
	let sec = Number(time.split(':')[2]);
	s = Number(hour * 3600) + Number(min * 60) + Number(sec);
	return s;
}

//将秒转化为时分秒
export const formatSecondsTime = (time) => {
	let theTime = parseInt(time); // 秒
	let theTime1 = 0; // 分
	let theTime2 = 0; // 小时
	// alert(theTime);
	if(theTime > 60) {
		theTime1 = parseInt(theTime / 60);
		theTime = parseInt(theTime % 60);
		// alert(theTime1+"-"+theTime);
		if(theTime1 > 60) {
			theTime2 = parseInt(theTime1 / 60);
			theTime1 = parseInt(theTime1 % 60);
		}
	};
	let str1 = String(formatTime(theTime2));
	let str2 = String(formatTime(theTime1));
	let str3 = String(formatTime(theTime));
	let arr = new Array();
	arr.push(str1, str2, str3);
	return arr;
}

//将秒转化为分秒
export const formatMineSecond = (time) => {
	let theTime = parseInt(time); // 秒
	let theTime1 = 0; // 分
	let theTime2 = 0; // 小时
	// alert(theTime);
	if(theTime > 60) {
		theTime1 = parseInt(theTime / 60);
		theTime = parseInt(theTime % 60);
		// alert(theTime1+"-"+theTime);
		if(theTime1 > 60) {
			theTime2 = parseInt(theTime1 / 60);
			theTime1 = parseInt(theTime1 % 60);
		}
	};
	let str1 = String(formatTime(theTime2));
	let str2 = String(formatTime(theTime1));
	let str3 = String(formatTime(theTime));
	str2 = String(formatTime(Number(str1 * 60) + Number(str2)));
	let arr = new Array();
	arr.push(str2, str3);
	return arr;
}

//计算2个日期相差的毫秒数
export const timeDiffer = (t1, t2) => {
	var dateBegin = new Date(t1.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateEnd = new Date(t2.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
	return dateDiff;
}

//将毫秒转化为日期
export const timeToData = (time) => {
	time = new Date(time);
	return time.getFullYear() + "/" + (time.getMonth() + 1) + "/" + time.getDate() + " " + time.getHours() + ":" + formatTime(time.getMinutes()) + ":" + formatTime(time.getSeconds());
}

//判断数字在数组的某个区间
export const valFindIndex = (array, val) => {
	if(val < Math.min.apply(null, array)) {
		return 0;
	};
	//如果值大于revenue最大的值时，则奖励最高一档
	if(!(val < Math.max.apply(null, array))) {
		return array.length - 1;
	};
	var idx = 0,
		i = 0,
		j = array.length;
	for(; i < j; i++) {
		if(array[i] > val) {
			idx = i;
			break;
		};
	};
	return idx - 1;
}

//处理ios返回空白
export const removeIOSwhite = (self) => {
	self.$nextTick(() => {
		window.scrollTo(0, 1);
		window.scrollTo(0, 0);
	})
};

//获取滚动条到顶端距离
export const getPositionY = () => {
	var scrollPos;
	if(window.pageYOffset) {
		scrollPos = window.pageYOffset;
	} else if(document.compatMode && document.compatMode != 'BackCompat') {
		scrollPos = document.documentElement.scrollTop;
	} else if(document.body) {
		scrollPos = document.body.scrollTop;
	}
	return scrollPos;
};

//返回顶部功能
export const smoothScrollTop = (val) => {
	(function smoothscroll() {
		let currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
		if(currentScroll > 0) {
			window.requestAnimationFrame(smoothscroll);
			window.scrollTo(0, currentScroll - (currentScroll / 5));
		}
	})();
};

/**
 * 滚动目标距离
 * @param {Object} coordinates x轴 y轴
 * @param {Object} el 父元素
 * @param {Object} val 目标距离
 */
export const objectiveDistance = (coordinates, element, val) => {
	let el = element,
		timer = null;
	clearTimeout(timer);
	if(coordinates == 'x') {
		// let le_width = el.getBoundingClientRect().width;
		// console.log('当前值：' + val + ',最大值：' + el.scrollWidth)
		// console.log()
		/* if (el.scrollLeft > val) {
			timer = setInterval(() => {
				el.scrollLeft = el.scrollLeft - 10;
				if (el.scrollLeft + le_width <= val) clearTimeout(timer);
			}, 10);
		} else if (el.scrollLeft < val) {
			timer = setInterval(() => {
				console.log(el.scrollLeft, val)
				el.scrollLeft = el.scrollLeft + 10;
				//console.log(el.scrollLeft)
				if (el.scrollLeft >= val) {
					el.scrollLeft = val;
					clearTimeout(timer);
				};
				if (el.scrollLeft + le_width >= el.scrollWidth) clearTimeout(timer);
			}, 10);
		} */

	} else if(coordinates == "y") {
		let le_height = Math.ceil(el.getBoundingClientRect().height);
		if(el.scrollTop > val) {
			timer = setInterval(() => {
				//console.log('el.scrollTop > val' + el.scrollTop, val)
				el.scrollTop = el.scrollTop - 40;
				if(el.scrollTop < val) el.scrollTop = val, clearTimeout(timer);
				if(el.scrollTop <= val) clearTimeout(timer);
			}, 10);
		} else if(el.scrollTop < val) {
			timer = setInterval(() => {
				//console.log('el.scrollTop < val' + el.scrollTop, val)
				el.scrollTop = el.scrollTop + 40;
				if(el.scrollTop > val) el.scrollTop = val, clearTimeout(timer);
				if(el.scrollTop >= val || el.scrollTop + le_height >= el.scrollHeight) clearTimeout(timer);
			}, 10);
		}
	} else {
		clearTimeout(timer);
	}
}

/**
 * @description 获取Url中的参数
 * @param name 参数名
 * @returns {*}  Url参数的值
 */
export const getQueryString = (name) => {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	var r = window.location.search.substr(1).match(reg);
	if(r != null) {
		return unescape(r[2]);
	}
	return null;
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 * 
 * 使用方法
 * methods:{
	getAliyunData:Throttle(function(){
	...
   },1000),
}
 * 
 */
export const Debounce = (fn, t) => {
	let delay = t || 500;
	let timer;
	//console.log(fn)
	//console.log(typeof fn)
	return function() {
		let args = arguments;
		if(timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			timer = null;
			fn.apply(this, args);
		}, delay);
	}
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t) => {
	let last;
	let timer;
	let interval = t || 500;
	return function() {
		let args = arguments;
		let now = +new Date();
		if(last && now - last < interval) {
			clearTimeout(timer);
			timer = setTimeout(() => {
				last = now;
				fn.apply(this, args);
			}, interval);
		} else {
			last = now;
			fn.apply(this, args);
		}
	}
};

/**
 * 获取当前时间24小时制   yyyy-MM-dd HH:mm:ss
 */
export const getDate24Hours = () => {
	let date = new Date();
	let _year = date.getFullYear(); //年
	let _month = date.getMonth() + 1; //月
	let _day = date.getDate(); //日
	let _hours = date.getHours(); //时
	let _minutes = date.getMinutes(); //分
	let _seconds = date.getSeconds(); //秒
	if(_month < 10) _month = '0' + _month;
	if(_day < 10) _day = '0' + _day;
	if(_hours < 10) _hours = '0' + _hours;
	if(_minutes < 10) _minutes = '0' + _minutes;
	if(_seconds < 10) _seconds = '0' + _seconds;
	let str = _year + "-" + _month + "-" + _day + " " + _hours + ":" + _minutes + ":" + _seconds;
	return str;
};
/**
 * 计算2个日期相差的天数 
 * 参数格式( yyyy-MM-dd HH:mm:ss)
 * faultDat 旧的时间     
 * completeTime  当前时间(新的时间)
 */
export const dateDiffIncludeToday = (faultDat, completeTime) => {
	var stime = Date.parse(new Date(faultDat)) || Date.parse(new Date(faultDat.replace(/-/g, '/')));
	var etime = Date.parse(new Date(completeTime)) || Date.parse(new Date(completeTime.replace(/-/g, '/')));
	//alert(stime + ',,' + etime)
	var usedTime = etime - stime; //两个时间戳相差的毫秒数
	var days = Math.floor(usedTime / (24 * 3600 * 1000));

	//计算出小时数
	var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));
	var time = days + "天" + hours + "时" + minutes + "分";
	return days;
};

/**
 * 去到 window 的Y轴位置
 * */
export const topWindScrollY = (val = 0) => {
	//document.documentElement.scrollTop = document.body.scrollTop = val;
	document.documentElement.scrollTop = document.body.scrollTop = window.pageYOffset = val;

}